package com.example.boosttestandroid.adapter;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import java.util.ArrayList;
import java.util.List;

public class MainFragmentAdapter {

    private List<Fragment> fragments = new ArrayList<>();

    /**
     * Fragment所属的Activity
     */
    private AppCompatActivity fragmentActivity;

    /**
     * Activity中所要被替换的区域的id
     */
    private int contentId;

    /**
     * 当前Tab页面索引
     */
    public int currentIndex = 0;

    public MainFragmentAdapter(List<Fragment> fragments, AppCompatActivity fragmentActivity, int contentId, int currentIndex) {
        this.fragments = fragments;
        this.fragmentActivity = fragmentActivity;
        this.contentId = contentId;
        this.currentIndex = currentIndex;

        initFragment();
        seletFragmentIndex(currentIndex);
    }

    private void initFragment() {
        FragmentTransaction ft = fragmentActivity.getSupportFragmentManager().beginTransaction();

        for (int i = 0; i < fragments.size(); i++) {
            ft.add(contentId, fragments.get(i));
        }
        ft.commitAllowingStateLoss();
    }

    public void seletFragmentIndex(int index){
        FragmentTransaction ft = fragmentActivity.getSupportFragmentManager().beginTransaction();

        for (int i = 0; i < fragments.size(); i++) {
            if (i == index) {
                ft.show(fragments.get(i));
            } else {
                ft.hide(fragments.get(i));
            }
        }
        ft.commitAllowingStateLoss();
    }

}
